<?php

namespace Payment\Common\WNFpay;

use Payment\Common\BaseData;
use Payment\Common\BaseStrategy;
use Payment\Common\PayException;
use Payment\Common\WnfConfig;
use Payment\Common\YSConfig;
use Payment\Utils\ArrayUtil;
use Payment\Utils\Curl;

abstract class WNFBaseStrategy implements BaseStrategy
{


    protected $config;

    /**
     * 支付数据
     * @var BaseData $reqData
     */
    protected $reqData;

    /**
     * FuBaseStrategy constructor.
     * @param array $config
     * @throws PayException
     */
    public function __construct(array $config)
    {
        /* 设置内部字符编码为 UTF-8 */
        mb_internal_encoding("UTF-8");

        try {
            $this->config = new WnfConfig($config);
        } catch (PayException $e) {
            throw $e;
        }
    }

    /**
     * 发送完了请求
     * @param $body
     * @return mixed
     * @throws \Payment\Common\PayException
     */
    protected function sendReq($body)
    {
        $url = $this->getReqUrl();
        if (is_null($url)) {
            throw new PayException('目前不支持该接口。请联系开发者添加');
        }
        $responseTxt = $this->curlPost($body, $url);
        return $responseTxt;
    }

    protected function curlPost($body, $url)
    {
        $curl = new Curl();
        return $curl->set([
            'CURLOPT_HEADER' => 0,
            'CURLOPT_HTTPHEADER' => ['Content-Type: application/json']
        ])->post($body, $url)->submit($url,false,true);
    }

    /**
     * 处理具体的业务
     *
     * @param array $data
     * @return mixed
     * @throws \Payment\Common\PayException
     */
    public function handle(array $data)
    {
        // TODO: Implement handle() method.
        $buildClass = $this->getBuildDataClass();
        try {
            $this->reqData = new $buildClass($this->config, $data);
        } catch (PayException $e) {
            throw $e;
        }

        $this->reqData->setSign();
        $body = $this->reqData->getData();

        $ret = $this->sendReq($body);
        
        return $this->retData($ret);
    }

    /**
     * 获取请求地址
     * @param null $url
     * @return string
     */
    protected function getReqUrl($url = null)
    {
        return $url ?? WnfConfig::PAY_URL;
    }

    /**
     * 处理支付平台的返回值并返回给客户端
     * @param array $ret
     * @return mixed
     *
     */
    protected function retData(array $ret)
    {
        return $ret['body'];
    }

}